package com.laicunba.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.laicunba.constant.GloabConstant;
import com.laicunba.pojo.AlertDO;
import com.laicunba.service.AlertService;
import com.laicunba.service.MobileMessageService;
import com.laicunba.util.CacheUtil;
import com.laicunba.util.RedisUtil;
import com.laicunba.util.StringUtil;
import com.laicunba.util.ThreadUtil;

@Service
public class AlertServiceImpl extends BaseServiceImpl implements AlertService {
	@Autowired
	private MobileMessageService mobileMessageService;

	@Override
	public void info(String message) {
		sendMessageToContactPerson(message);
	}

	private void sendMessageToContactPerson(String message) {
		if (StringUtil.isNotEmpty(GloabConstant.ALERT_MOBILES)) {
			for (String mobile : GloabConstant.ALERT_MOBILES.split(",")) {
				mobileMessageService.sendMsgAsync(mobile, message);

			}
		}
	}

	@Override
	public void error(String message) {
		sendMessageToContactPerson(message);
	}

	@Override
	public void info2Manager(String message) {
		if (StringUtil.isNotEmpty(GloabConstant.ALERT_MANAGER_MOBILES)) {
			for (String mobile : GloabConstant.ALERT_MANAGER_MOBILES.split(",")) {
				mobileMessageService.sendMsgAsync(mobile, message);
			}
		}

	}

	@Override
	public void keepalived(final String tag) {
		ThreadUtil.execute(new Runnable() {

			@Override
			public void run() {
				RedisUtil.hset("keepalived", tag, Long.toString(System.currentTimeMillis()));
			}
		});
	}

	@Override
	public void info(String uid, String message) {
		createDBLog(uid, "info", message);
	}

	private void createDBLog(String uid, String level, String message) {
		final AlertDO alertDO = new AlertDO();
		alertDO.setUserId(StringUtil.isNotEmpty(uid) ? uid : "sys");
		alertDO.setLevel(level);
		alertDO.setContent(message);
		ThreadUtil.execute(new Runnable() {

			@Override
			public void run() {
				create(alertDO);
			}
		});

	}

	@Override
	public void warn(String uid, String message) {
		createDBLog(uid, "warn", message);
	}

	@Override
	public void error(String uid, String message) {
		createDBLog(uid, "error", message);
	}

}
